package com.itheima.reggie.filter;



import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: wf
 * @Desc: 过滤器，检查用户是否已经登录
 * @Date: 2022-08-16 21:32:46
 */
// filterName = "LoginCheckFilter" 可以省略
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    // 路径匹配器，支持通配符
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        // 1获取本次请求的URI
        String requestURI = request.getRequestURI();
        log.info("拦截的请求：{}",requestURI);
        // 定义不需要处理的请求路径
        String[] urlStr = {"/backend/**",
                            "/front/**",
                            "/employee/login",
                            "/employee/logout",
                            "/user/login",
                            "/user/sendMsg"
        };
        // 2、判断本次请求是否需要处理
        boolean check = check(urlStr, requestURI);
        // 3、如果不需要处理则直接放行
        if (check) {
            log.info("本次请求{}不需要处理", requestURI);
            chain.doFilter(request, response);
            return;
        }
        // 4.1、判断登录状态，如果已经登录，则直接放行
        if (request.getSession().getAttribute("employee") != null) {
            log.info("用户已登录，id:{}",request.getSession().getAttribute("employee"));
            BaseContext.setCurrentId((Long)request.getSession().getAttribute("employee"));
            chain.doFilter(request, response);
            return;
        }
        // 4.2、判断登录状态，如果已经登录，则直接放行
        if (request.getSession().getAttribute("user") != null) {
            log.info("用户已登录，id:{}",request.getSession().getAttribute("user"));
            BaseContext.setCurrentId((Long)request.getSession().getAttribute("user"));
            chain.doFilter(request, response);
            return;
        }
        // 5、如果没有登录，则返回没有登录结果，通过输出流的方式向页面响应数据
        log.info("用户没有登录");

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 功能描述: 路径匹配，检查本次请求是否需要放行
     * @param urlStr
     * @param requestURI
     * @return boolean
     */
    private boolean check(String[] urlStr, String requestURI) {
        for (String url : urlStr) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
